import java.util.Stack;

public class 最长有效括号 {
    public static void main(String[] args) throws Exception {
        String s="()(()";
        int i = longestValidParentheses(s);
        System.out.println(i);
    }
    public static int longestValidParentheses(String s) throws Exception{
        if (s==null ||s.length()==0){
            return 0;
        }
        Stack<String> stack = new Stack<>();
        int count=0;
        for (int i = 0; i < s.length(); i++) {
            String c=s.charAt(i)+"";
            if (c.equals("(")) {
                stack.push(")");
            }
            if (c.equals(")")){
                //解决空栈问题
                if (stack.size()==0){
                    continue;
                }
                String pop = stack.pop();
                if (pop!=null){
                    count+=2;
                }
            }
           }
        return count;
    }
}
